package com.asd.netty.netty.client;


import com.asd.netty.netty.common.PacketProto;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import static com.asd.netty.netty.common.PacketProto.Packet.newBuilder;
import java.util.Random;
import java.util.UUID;


/**
 * @author LRL
 */
@Slf4j
public class NettyClient {

//    public static String host = "221.12.76.139";
public static String host = "192.168.31.221";

    public static int port = 5019;
    private static Channel ch;
    private static Bootstrap bootstrap;
    public static void main(String[] args) {
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            bootstrap = new Bootstrap();
            bootstrap
                    .group(workGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ClientHeartbeatInitializer());
            /**连接服务器**/
            doConnect();

            /**模拟不定时发送向服务器发送数据的过程**/
            Random random = new Random();
            while (true) {
                UUID uuid = UUID.randomUUID();
                String str = uuid.toString();
//                int num = random.nextInt(21);
                String num = "-123A OA:00 AF";
//                String num = str.substring(1, 15);
                log.info("客户端发送数据： "+ num);
                Thread.sleep(9000);
                //Thread.sleep(random.nextInt(9)*1000);
                PacketProto.Packet.Builder builder = newBuilder();
                builder.setPacketType(PacketProto.Packet.PacketType.DATA);
                builder.setData(num);
                PacketProto.Packet packet = builder.build();
                ch.writeAndFlush(packet);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workGroup.shutdownGracefully();
        }
    }

    /**
     * 抽取出该方法 (断线重连时使用)
     *
     * @throws InterruptedException
     */
    public static void doConnect() throws InterruptedException {
        ch = bootstrap.connect(host,port).sync().channel();
    }
}
